<template>
  <el-dialog
    :visible="visible"
    :title="title"
    class="build-edit-dialog"
    align-center
    :append-to-body="true"
    @opened="handleDialogOpen"
    @close="closeDialog"
    width="70%"
  >
    <el-form
      :model="form"
      :disabled="disabled"
      :rules="formRules"
      ref="formRef"
      label-width="160px"
    >
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item prop="communityId" label="所属社区">
            <el-cascader
              v-model="areaInfo"
              :options="communityInfoList"
              :props="casxaderProps"
              placeholder="请选择社区"
              class="area-cascader"
              :show-all-levels="false"
              @change="handleChangeArea"
              clearable
            ></el-cascader> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item prop="residenceId" label="所属小区">
            <el-select v-model="form.residenceId" placeholder="请选择小区">
              <el-option
                v-for="item in residenceList"
                :key="item.pkid"
                :label="item.areaName"
                :value="item.pkid"
              ></el-option>
            </el-select> </el-form-item
        ></el-col>
      </el-row>
      <el-row
        :gutter="24"
        v-show="!isPoint && (roleLevel === 0 || roleLevel === 4)"
      >
        <el-col :span="24" class="special-title">
          <i class="el-icon"></i>
          <span>楼宇基础信息</span>
        </el-col>
      </el-row>
      <el-row
        :gutter="24"
        v-show="!isPoint && (roleLevel === 0 || roleLevel === 4)"
      >
        <el-col
          v-for="(item, index) in baseInfoTable"
          :key="index"
          :span="item.span || 12"
        >
          <el-form-item
            label-width="180px"
            :label="item.label"
            :prop="item.prop"
          >
            <template v-if="item.type === 'input'">
              <el-input
                v-model="form[item.prop]"
                :placeholder="item.placeholder"
                :disabled="item.disabled"
              ></el-input>
            </template>
            <template v-if="item.type === 'image'">
              <el-upload
                action=""
                class="upload-demo"
                :on-preview="
                  (file) => handlePictureCardPreview(file, item.prop)
                "
                :on-change="
                  (file, fileList) =>
                    handlePictureCardChange(file, fileList, item.prop)
                "
                :on-remove="
                  (file, fileList) =>
                    handlePictureRemove(file, fileList, item.prop)
                "
                :file-list="form[item.prop]"
                list-type="picture-card"
                :auto-upload="false"
                accept="image/*"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </template>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" v-show="!isPoint">
        <el-col :span="24" class="special-title">
          <i class="el-icon"></i>
          <span>楼宇核实</span>
        </el-col>
      </el-row>
      <el-row :gutter="24" v-show="!isPoint">
        <el-col :span="24" v-for="(item, index) in otherInfoTable" :key="index">
          <el-form-item
            label-width="180px"
            :label="item.label"
            :prop="item.prop"
          >
            <template v-if="item.type === 'input'">
              <el-input
                v-model="form[item.prop]"
                :placeholder="item.placeholder"
                :disabled="item.disabled"
              ></el-input>
            </template>
            <template v-if="item.type === 'textarea'">
              <el-input
                type="textarea"
                v-model="form[item.prop]"
                :rows="3"
                :placeholder="item.placeholder"
                :disabled="item.disabled"
              ></el-input>
            </template>
            <template v-if="item.type === 'image'">
              <el-upload
                action=""
                class="upload-demo"
                :on-preview="
                  (file) => handlePictureCardPreview(file, item.prop)
                "
                :on-change="
                  (file, fileList) =>
                    handlePictureCardChange(file, fileList, item.prop)
                "
                :on-remove="
                  (file, fileList) =>
                    handlePictureRemove(file, fileList, item.prop)
                "
                :file-list="form[item.prop]"
                list-type="picture-card"
                :auto-upload="false"
                accept="image/*"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </template>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="24" class="special-title">
          <i class="el-icon"></i>
          <span>楼宇隐患信息</span>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col
          class="special-info-item"
          :span="24"
          v-for="(item, index) in specialInfoTable"
          :key="index"
        >
          <div class="item-title">{{ item.title }}</div>
          <div class="item-remark">{{ item.remark }}</div>
          <el-form-item
            v-for="(subItem, subIndex) in item.questions"
            :key="subIndex"
            :label="subItem.label"
            :prop="subItem.prop"
          >
            <template v-if="subItem.type === 'radio'">
              <el-radio-group
                v-model="form[subItem.prop]"
                :disabled="getDisabled(subItem.disabledField)"
              >
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </template>
            <template v-if="subItem.type === 'textarea'">
              <el-input
                type="textarea"
                v-model="form[subItem.prop]"
                :rows="3"
                :placeholder="subItem.placeholder"
                :disabled="getDisabled(subItem.disabledField)"
              ></el-input>
            </template>
            <template v-if="subItem.type === 'select'">
              <el-radio-group
                v-model="form[subItem.prop]"
                :disabled="getDisabled(subItem.disabledField)"
              >
                <el-radio
                  v-for="(option, optionIndex) in subItem.options"
                  :key="optionIndex"
                  :label="option.label"
                >
                  {{ option.label }}
                </el-radio>
              </el-radio-group>
            </template>
            <template v-if="subItem.type === 'image'">
              <el-upload
                action=""
                class="upload-demo"
                :on-preview="
                  (file) => handlePictureCardPreview(file, subItem.prop)
                "
                :on-change="
                  (file, fileList) =>
                    handlePictureCardChange(file, fileList, subItem.prop)
                "
                :on-remove="
                  (file, fileList) =>
                    handlePictureRemove(file, fileList, subItem.prop)
                "
                :file-list="form[subItem.prop]"
                list-type="picture-card"
                :auto-upload="false"
                accept="image/*"
                :disabled="getDisabled(subItem.disabledField)"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </template>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <image-viewer
      :z-index="9999"
      v-if="previewVisible"
      :url-list="previewList"
      :onClose="() => (previewVisible = false)"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit"> 确定 </el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  computed,
  getCurrentInstance,
  onMounted,
  reactive,
  ref,
  watch,
} from 'vue'
import {
  addSubProjectInventory,
  updateSubProjectInventory,
} from '@/api/project-update/sub-project-inventory'
import { Message } from 'element-ui'
import { getProjectInventoryList } from '@/api/project-update/project-inventory'
import {
  baseInfoTable,
  otherInfoTable,
  specialInfoTable,
} from '@/views/one-map/left-community-info/build-edit-config'
import ImageViewer from 'element-ui/packages/image/src/image-viewer.vue'
import {
  addOrUpdateBuilding,
  addOrUpdatePoint,
  getBuildingInfo,
  getPoint,
} from '@/api/building'
import { queryList, uploadFile } from '@/api/question'
import { baseFileUrl } from '@/utils'

const vm = getCurrentInstance()

const getDisabled = (field) => {
  if (!field) return false
  return Array.isArray(field)
    ? field.some((item) => form[item] !== 1)
    : form[field] !== 1
}

const previewList = ref([])
const previewVisible = ref(false)

const handlePictureCardChange = async (file, fileList, prop) => {
  file.orderIndex = fileList.length
  try {
    const formData = new FormData()
    formData.append('file', file.raw)
    formData.append('type', 'building')
    const res = await uploadFile(formData)
    if (res.success) {
      file.fileId = res.data
    } else {
      Message.error(res.message)
    }
  } catch (e) {
    Message.error('上传失败')
  }
  form[prop] = fileList
}

const handlePictureRemove = (file, fileList, prop) => {
  // const index = fileList.indexOf(file)
  // fileList.splice(index, 1)
  form[prop] = fileList
}

const handlePictureCardPreview = (file, props) => {
  // window.open(file.url, '_blank')
  previewList.value = form[props]?.map((item) => item.url) || []
  previewVisible.value = true
}

const disabled = ref(false)

const user = JSON.parse(localStorage.getItem('user')).user

const findNodeById = (tree, targetId) => {
  // console.log(tree, targetId)
  // 遍历树中的每个节点
  for (let i = 0; i < tree.length; i++) {
    // 检查当前节点的ID是否为目标ID
    if (tree[i].areaCode === targetId || tree[i].pkid === targetId) {
      // 如果是的话，返回当前节点
      return tree[i]
    }

    // 如果当前节点有子节点，则递归在子节点中查找
    if (tree[i].children && tree[i].children.length > 0) {
      const foundNode = findNodeById(tree[i].children, targetId)
      // 如果在子节点中找到了，则返回找到的节点
      if (foundNode !== undefined) {
        return foundNode
      }
    }
  }

  // 如果在树中没有找到目标ID，则返回undefined
  return undefined
}

const deleteLastLevel = (tree) => {
  tree.map((item) => {
    if (item.children && item.children.length > 0) {
      deleteLastLevel(item.children)
    } else {
      delete item.children
    }
  })
}

const communityInfoList = computed(() => {
  const refId = user.refId
  const find = findNodeById(props.cityList, refId)
  let arr = []
  if (find) {
    arr = [find]
    deleteLastLevel(arr)
  }
  return arr
})

const casxaderProps = {
  value: 'areaCode',
  label: 'areaName',
  // checkStrictly: true,
  children: 'children',
}
const areaInfo = ref([])

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '楼宇详情',
  },
  item: {
    type: Object,
    default: () => ({}),
  },
  cityList: {
    type: Array,
    default: () => [],
  },
  // 建筑物编码
  buildCode: {
    type: String,
    default: '',
  },
  // 查询时的主键
  pkid: {
    type: String,
    default: '',
  },
  isPoint: {
    type: Boolean,
    default: false,
  },
  roleLevel: {
    type: Number,
    default: -1,
  },
})

const emit = defineEmits(['closeDialog', 'updateData'])

const resetForm = () => {
  Object.keys(form).forEach((key) => {
    const value = form[key]
    if (Array.isArray(value)) {
      form[key] = []
    } else {
      form[key] = ''
    }
  })
  form.communityId = ''
  form.residenceId = ''
  areaInfo.value = []
}

const closeDialog = () => {
  resetForm()
  emit('closeDialog')
}

const updateData = () => {
  resetForm()
  emit('updateData')
}

const form = reactive({
  communityId: '',
  residenceId: '',
})

const handleChangeArea = (val) => {
  form.communityId = val[val.length - 1]
  form.residenceId = ''
}

const formRef = ref()

const formRules = reactive({
  // communityId: [{ required: true, message: '请选择社区', trigger: 'change' }],
  // residenceId: [{ required: true, message: '请选择小区', trigger: 'change' }],
})

function findParentIds(tree, targetId) {
  const result = []

  function findPath(node, path) {
    if (node.pkid === targetId) {
      result.push(...path)
      return true
    }

    if (node.children) {
      for (let child of node.children) {
        if (findPath(child, [...path, node.pkid])) {
          return true
        }
      }
    }
    return false
  }

  for (let node of tree) {
    if (findPath(node, [])) {
      break
    }
  }

  return result
}

const handleDialogOpen = () => {
  if (props.pkid) {
    if (props.isPoint) {
      getPoint(props.pkid).then((res) => {
        if (res.success) {
          const data = res.data || {}
          const topicBuildFileVo = data.topicBuildFileVo || {}
          const topicNewPointInfo = data.topicNewPointInfo || {}
          Object.assign(form, {
            ...topicNewPointInfo,
            ...topicBuildFileVo,
          })
          Object.keys(form).forEach((key) => {
            if (Array.isArray(form[key])) {
              form[key] = form[key].map((item) => {
                return {
                  ...item,
                  url: baseFileUrl + item.filePath,
                  name: item.fileName,
                  status: 'finished',
                }
              })
            }
          })
          form.buildFile = []
          form.buildBaseFile = []
          const parents = findParentIds(props.cityList, form.communityId)
          parents.push(form.communityId)
          areaInfo.value = parents
        } else {
          Message.error(res.message)
        }
      })
      return
    }
    getBuildingInfo(props.pkid).then((res) => {
      if (res.success) {
        const data = res.data || {}
        const topicBuildFileVo = data.topicBuildFileVo || {}
        const topicNewBuildInfo = data.topicNewBuildInfo || {}
        topicNewBuildInfo.buildInfoPkid = topicNewBuildInfo.pkid || ''
        const topicNewBuildRel = data.topicNewBuildRel || {}
        topicNewBuildRel.buildRelPkid = topicNewBuildRel.pkid || ''
        Object.assign(form, {
          ...topicNewBuildInfo,
          ...topicNewBuildRel,
          ...topicBuildFileVo,
        })
        Object.keys(form).forEach((key) => {
          if (Array.isArray(form[key])) {
            form[key] = form[key]
              .filter((file) => file.filePath)
              .map((item) => {
                return {
                  ...item,
                  url: baseFileUrl + item.filePath,
                  name: item.fileName,
                  status: 'finished',
                }
              })
          }
        })
        if (!form.buildCode) {
          form.buildCode = props.buildCode
        }
        if (form.communityId) {
          const parents = findParentIds(props.cityList, form.communityId)
          parents.push(form.communityId)
          areaInfo.value = parents
        }
      } else {
        Message.error(res.message)
      }
    })
  }
}

const onSubmit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      const topicBuildFileVo = {}
      const topicNewBuildRel = {}
      const topicNewBuildInfo = {}
      if (!props.isPoint) {
        baseInfoTable.forEach((item) => {
          if (item.type === 'image') {
            topicBuildFileVo[item.prop] = form[item.prop]
          } else {
            topicNewBuildInfo[item.prop] = form[item.prop]
          }
        })
        topicNewBuildInfo.pkid = form.buildInfoPkid
        topicNewBuildInfo.buildCode = form.buildCode || props.buildCode
        topicNewBuildInfo.buildId = form.buildId || props.pkid
        topicNewBuildInfo.refId = form.refId
        otherInfoTable.forEach((item) => {
          if (item.type === 'image') {
            topicBuildFileVo[item.prop] = form[item.prop]
          } else {
            topicNewBuildRel[item.prop] = form[item.prop]
          }
        })
      } else {
        topicNewBuildRel.pkid = form.pkid
        topicNewBuildRel.point = form.point
      }
      const len = specialInfoTable.length
      for (let i = 0; i < len; i++) {
        const item = specialInfoTable[i]
        const len2 = item.questions.length
        for (let j = 0; j < len2; j++) {
          const subItem = item.questions[j]
          if (subItem.type === 'image') {
            if (subItem.disabledField) {
              if (getDisabled(subItem.disabledField)) {
                topicBuildFileVo[subItem.prop] = []
                continue
              }
            }
            topicBuildFileVo[subItem.prop] = form[subItem.prop]
          } else {
            if (subItem.disabledField) {
              if (getDisabled(subItem.disabledField)) {
                if (subItem.type === 'select' || subItem.type === 'textarea') {
                  topicNewBuildRel[subItem.prop] = ''
                } else {
                  topicNewBuildRel[subItem.prop] = 0
                }
                continue
              } else {
                if (subItem.type === 'select' && !form[subItem.prop]) {
                  Message.error(
                    `请选择${subItem.label}，前置项选择是后必须选择等级`
                  )
                  return
                }
              }
            }
            topicNewBuildRel[subItem.prop] = form[subItem.prop]
          }
        }
      }
      topicNewBuildRel.communityId = form.communityId
      topicNewBuildRel.residenceId = form.residenceId
      if (!props.isPoint) {
        topicNewBuildRel.buildCode = form.buildCode || props.buildCode
        topicNewBuildRel.pkid = form.buildRelPkid
      }
      let data = {
        topicBuildFileVo,
        topicNewBuildInfo,
        topicNewBuildRel,
      }
      if (props.isPoint) {
        data = {
          topicBuildFileVo,
          topicNewPointInfo: topicNewBuildRel,
        }
      } else {
        if (props.roleLevel !== 0 && props.roleLevel !== 4) {
          data = {
            topicBuildFileVo,
            topicNewBuildRel,
          }
        }
      }
      let promise
      if (props.isPoint) {
        promise = addOrUpdatePoint(data)
      } else {
        promise = addOrUpdateBuilding(data)
      }
      promise.then((res) => {
        if (res.success) {
          Message.success(res.data)
          updateData()
        } else {
          Message.error(res.message)
        }
      })
    }
  })
}

const residenceList = ref([])

watch(
  () => form.communityId,
  async (val) => {
    if (!val) return
    try {
      queryList(
        {
          communityId: val,
        },
        'residence'
      ).then((res) => {
        if (res.success) {
          residenceList.value =
            res.data?.list?.map((item) => {
              return {
                pkid: item.pkid,
                areaName: item.name,
              }
            }) || []
        } else {
          Message.error(res.message)
        }
      })
    } catch (e) {
      residenceList.value = []
    }
  }
)

onMounted(() => {
  baseInfoTable.forEach((item) => {
    if (item.type === 'image') {
      vm?.proxy.$set(form, item.prop, [])
    } else {
      vm?.proxy.$set(form, item.prop, '')
    }
  })
  otherInfoTable.forEach((item) => {
    if (item.type === 'image') {
      vm?.proxy.$set(form, item.prop, [])
    } else {
      vm?.proxy.$set(form, item.prop, '')
    }
  })
  specialInfoTable.forEach((item) => {
    item.questions.forEach((subItem) => {
      if (subItem.type === 'image') {
        vm?.proxy.$set(form, subItem.prop, [])
      } else {
        vm?.proxy.$set(form, subItem.prop, '')
      }
    })
  })
})
</script>

<style lang="scss">
.build-edit-dialog {
  //width: 762px;
  //height: 704px;
  //background: #ffffff;
  border-radius: 4px;

  .el-dialog__header {
    border-bottom: 1px solid #e5e5e5;

    .el-dialog__title {
      width: 64px;
      height: 16px;
      font-size: 16px;
      font-weight: bold;
      color: #27475f;
    }
  }

  .el-form {
    .special-title {
      margin-top: 5px;
      margin-bottom: 8px;
      display: flex;
      align-items: center;

      .el-icon {
        width: 3px;
        height: 18px;
        margin-right: 6px;
        background-color: #28b1e4;
        border-radius: 2px;
      }

      span {
        font-size: 14px;
        font-weight: bold;
      }
    }

    .special-info-item {
      padding-left: 30px !important;
      padding-right: 30px !important;
      .item-remark {
        margin-top: 10px;
        margin-bottom: 10px;
        font-size: 12px;
        color: #999999;
      }
    }

    //margin-bottom: 336px;
    .el-form-item {
      min-height: 42px;
      margin-bottom: 11px;
      align-items: center;
    }

    .el-cascader {
      width: 100%;
    }

    .el-select {
      width: 100%;
    }
  }

  .el-dialog__body {
    max-height: 600px;
    overflow-y: auto;
  }

  .el-dialog__footer {
    padding-top: 30px;
    border-top: 1px solid #e5e5e5;
  }

  .dialog-footer {
    width: 100%;
    height: 100%;
    text-align: center;
  }
}
</style>
